package cn.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cn.domain.Api;
import cn.domain.Apipra;
import cn.domain.Cate;
import cn.domain.Log;
import cn.domain.Proj;
import cn.domain.User;
import cn.entity.Apis;
import cn.entity.LogJsp;
import cn.util.HttpUtils;
import cn.util.Pagination;

/**
 * 
 * @项目名称:pigbaby
 * @类名称:ApkAction
 * @类描述:移动设备的所有接口
 * @创建人:陈凯
 * @创建时间:20150713 17：23 星期一
 * @修改人:
 * @修改时间:
 * 
 * @修改备注:
 * @version
 */
@Namespace("/")
@Scope("prototype")
@ParentPackage("json-default")
@Component("apiAction")
@Action(value = "apiAction", results = { 
		@Result(name = "loginout", location = "/login.jsp"),
		@Result(name = "add", location = "/apiadd.jsp"),
		@Result(name = "edit", location = "/apiedit.jsp"),
		@Result(name = "info", location = "/apieditandinfo.jsp"),
		@Result(name = "test", location = "/test.jsp"),
		@Result(name = "resultjson", type = "json")
		})
public class ApiAction extends BaseAction {

	// 保存日志
	public static Logger logger = LoggerFactory.getLogger(ApiAction.class);
	private String deleteId;
	private Cate cate;
	private Api api;
	private Apis apis;
	private List<User> users;
	private List<Proj> projlist;
	private List<Cate> catelist;
	private List<Api> apilist;
	private List<Apipra> apipralist;
	private List<LogJsp> logJsps;
	private String des;
	private String debugURL;
	private String apiid;
	private String apiname;
	/**
	 * 是否必填 add by caishuangxi
	 */
	private String required;
	
	public String gotoapiedit() throws UnsupportedEncodingException{
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		if(null != cate && null != cate.getPid()){
			projlist = projService.getProjsById(cate.getPid());
		}else{
			projlist = projService.getAll();
		}
		
		if(null != cate && null != cate.getAid()){
			if(null == api){
				api = new Api();
			}
			api.setAid(cate.getAid());
			catelist = cateService.getCatesByAid(cate.getAid());
		}else{
			catelist = cateService.getAll();
		}
			
		if(null != api && null != api.getCname() && !"".equals(api.getCname().trim())){
			api.setCname(new String(api.getCname().getBytes("iso8859-1"),"UTF-8"));
		}
		des = api==null?"":api.getCname();
		apilist = apiService.getAll(api);
		users = userService.getAll();
		return "edit";
	}
	
	public String gotoapieditandinfo() throws UnsupportedEncodingException{
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		if(api == null){
			return "edit";
		}
		if(null != cate && null != cate.getPid()){
			projlist = projService.getProjsById(cate.getPid());
		}else{
			projlist = projService.getAll();
		}
		
		if(null != cate && null != cate.getAid()){
			if(null == api){
				api = new Api();
			}
			api.setAid(cate.getAid());
			catelist = cateService.getCatesByAid(cate.getAid());
		}else{
			catelist = cateService.getAll();
		}
		if(null != api && null != api.getCname() && !"".equals(api.getCname().trim())){
			api.setCname(new String(api.getCname().getBytes("iso8859-1"),"UTF-8"));
		}		
		des = api==null?"":api.getCname();
		apilist = apiService.getAll(api);
		api = apiService.selectOne(api.getId()+"");
		cate = cateService.selectOne(api.getAid()+"");
		apipralist = apipraService.getListByAid(api.getId());
		logJsps = logService.getAllByApiid(api.getId());
		users = userService.getAll();
		return "info";
	}

	public String gototest() throws UnsupportedEncodingException{
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		if(null != cate && null != cate.getPid()){
			projlist = projService.getProjsById(cate.getPid());
		}else{
			projlist = projService.getAll();
		}
		
		if(null != cate && null != cate.getAid()){
			if(null == api){
				api = new Api();
			}
			api.setAid(cate.getAid());
			catelist = cateService.getCatesByAid(cate.getAid());
		}else{
			catelist = cateService.getAll();
		}
		if(null != api && null != api.getCname() && !"".equals(api.getCname().trim())){
			api.setCname(new String(api.getCname().getBytes("iso8859-1"),"UTF-8"));
		}
		des = api==null?"":api.getCname();
		apilist = apiService.getAll(api);
		api = apiService.selectOne(api.getId()+"");
		cate = cateService.selectOne(api.getAid()+"");
		apipralist = apipraService.getListByAid(api.getId());
		logJsps = logService.getAllByApiid(api.getId());
		users = userService.getAll();
		return "test";
	}
	public String gotoapiadd() throws UnsupportedEncodingException{
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		if(null != cate && null != cate.getPid()){
			projlist = projService.getProjsById(cate.getPid());
		}else{
			projlist = projService.getAll();
		}
		
		if(null != cate && null != cate.getAid()){
			if(null == api){
				api = new Api();
			}
			api.setAid(cate.getAid());
			catelist = cateService.getCatesByAid(cate.getAid());
		}else{
			catelist = cateService.getAll();
		}
		if(null != api && null != api.getCname() && !"".equals(api.getCname().trim())){
			api.setCname(new String(api.getCname().getBytes("iso8859-1"),"UTF-8"));
		}
		des = api==null?"":api.getCname();
		apilist = apiService.getAll(api);
		users = userService.getAll();
		return "add";
	}
	
	public String destroy(){
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		if(deleteId != null && !"".equals(deleteId)){
			apiService.delete(deleteId);
		}
		outJSONMessage("success");
		return "resultjson";
	}

	public String insert(){
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		for(int i=0;i<apis.getApipras().size();i++){
			Apipra ap = apis.getApipras().get(i);
			if("".equals(ap.getCname())){
				outJSONMessage("请求参数列表，第( "+(i+1)+" )行【名称】不能为空！");
				return "resultjson";
			}
			if("".equals(ap.getType())){
				outJSONMessage("请求参数列表，第( "+(i+1)+" )行【类型】不能为空！");
				return "resultjson";
			}
		}
		apis.setAid(cate.getAid());
		if(apiService.getOne(apis)){
			outJSONMessage("该接口已经存在！");
		}else{
			apis.setIsdel(0);
			apis.setAid(cate.getAid());
			apis.setApiuser(user.getId());
			apiService.insert(apis);
			outJSONMessage("success");
		}
		return "resultjson";
	}
	
	public String updateApi(){
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		for(int i=0;i<apis.getApipras().size();i++){
			Apipra ap = apis.getApipras().get(i);
			if("".equals(ap.getCname())){
				outJSONMessage("请求参数列表，第( "+(i+1)+" )行【名称】不能为空！");
				return "resultjson";
			}
			if("".equals(ap.getType())){
				outJSONMessage("请求参数列表，第( "+(i+1)+" )行【类型】不能为空！");
				return "resultjson";
			}
		}
		Api api_db = apiService.selectOne(apis.getId()+"");
		List<Apipra> apipras_db = apipraService.getListByAid(apis.getId());
		
		
		if(!api_db.getCname().equals(apis.getCname())){
			apis.setAid(cate.getAid());
			if(apiService.getOne(apis)){
				outJSONMessage("该模块已经存在！");
			}else{
				apis.setIsdel(0);
				apis.setAid(cate.getAid());
				apis.setApiuser(user.getId());
				apiService.update(apis,api_db,apipras_db);
				outJSONMessage("success");
			}
		}else {
			apis.setIsdel(0);
			apis.setAid(cate.getAid());
			apis.setApiuser(user.getId());
			apiService.update(apis,api_db,apipras_db);
			outJSONMessage("success");
		}
		
		return "resultjson";
	}
	
	public String list() throws UnsupportedEncodingException{
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		String pagestr = request.getParameter("page");
		pageIndex = Integer.parseInt(pagestr);
		String search = "";
		if(cate.getCname() != null && !"".equals(cate.getCname())){
			search = new String(cate.getCname().getBytes("iso8859-1"),"UTF-8");
		}
		total = cateService.getAllCount(cate);
		pagination = new Pagination(pageIndex,rows,total);
		pagination.setId(cate.getPid());
		pagination.setSearch(search);
		List<Cate> list = cateService.getAlllist(pagination);
		outJSONList(list,total);
		return "resultjson";
	}

	public String updatestatus(){
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		Api api_db = apiService.selectOne(api.getId()+"");
		api_db.setIsok(api.getIsok());
		apiService.updateStatus(api_db);
		outJSONMessage("success");
		return "resultjson";
	}
	
	public String debugInterface() throws IOException{
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		if(null != debugURL && !"".equals(debugURL.trim())){			
			outJSONMessage(apiService.debugInterface(debugURL,user.getId(),Integer.parseInt(apiid),apiname));
		}else{
			outJSONMessage("error");
		}
		return "resultjson";
	}
	
	/**
	 * 
	 * @author: caishuangxi
	 * @date: 2016年4月7日 上午10:36:03	
	 * @Title: debugInterface2 
	 * @Description: TODO
	 * @return
	 * @throws IOException
	 * @return: String
	 */
	public String debugInterface2() throws Exception{
		User user = (User)request.getSession().getAttribute("user");
		if(user == null){
			return "loginout";
		}
		
		//字段
		String[] field = request.getParameterValues("field");
		//类型
		String[] types = request.getParameterValues("type");
		//值
		String[] value = request.getParameterValues("value");
		
		
		JSONObject in = new JSONObject();
		JSONObject body = new JSONObject();
		JSONObject head = new JSONObject();
		
		
		boolean flag = false;
		if(field!=null && field.length>0){
			for(int i=0;i<field.length;i++){
					String f = field[i];

					if(f.contains("head.")){
						head.put(f.substring(f.indexOf("head.")+5, f.length()), value[i]);
					}
					if(f.contains("body.")){
						body.put(f.substring(f.indexOf("body.")+5, f.length()), value[i]);
					}
					
					if(f.equals("body") && (types[i].equals("JSON") || types[i].equals("JSONARRAY"))){
						in.put("body", value[i]);
						flag = true;
					}
					
			}
			
		}
		
		in.put("head", head);
		if(!flag){
			in.put("body", body);
		}
		
		String sbResult = HttpUtils.doPost(debugURL, in);
		
		Log log = new Log();
		log.setInserttime(new Date());
		log.setUid(user.getId());
		log.setApiid(apis.getId());
		log.setTitle("接口");
		log.setBody("测试接口"+"【"+apis.getCname()+"】</br>"+"接口请求URL【"+debugURL+"】</br>测试请求【"+in.toString()+"】</br>测试结果【"+sbResult+"】");
		//logMapper.insert(log);
		apiService.insertLog(log);
		
		JSONObject out = new JSONObject();
		
		out.put("request", in);
		
		out.put("response", sbResult);
		
		
		
		if(null != debugURL && !"".equals(debugURL.trim())){			
			outJSONMessage(out);
		}else{
			out.put("error", "error");
			outJSONMessage(out);
		}
		return "resultjson";
	}
	
	public String getDeleteId() {
		return deleteId;
	}

	public void setDeleteId(String deleteId) {
		this.deleteId = deleteId;
	}

	public Cate getCate() {
		return cate;
	}

	public void setCate(Cate cate) {
		this.cate = cate;
	}

	public Api getApi() {
		return api;
	}

	public void setApi(Api api) {
		this.api = api;
	}

	public Apis getApis() {
		return apis;
	}

	public void setApis(Apis apis) {
		this.apis = apis;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public List<Proj> getProjlist() {
		return projlist;
	}

	public void setProjlist(List<Proj> projlist) {
		this.projlist = projlist;
	}

	public List<Cate> getCatelist() {
		return catelist;
	}

	public void setCatelist(List<Cate> catelist) {
		this.catelist = catelist;
	}

	public List<Api> getApilist() {
		return apilist;
	}

	public void setApilist(List<Api> apilist) {
		this.apilist = apilist;
	}

	public List<Apipra> getApipralist() {
		return apipralist;
	}

	public void setApipralist(List<Apipra> apipralist) {
		this.apipralist = apipralist;
	}

	public List<LogJsp> getLogJsps() {
		return logJsps;
	}

	public void setLogJsps(List<LogJsp> logJsps) {
		this.logJsps = logJsps;
	}

	public String getDes() {
		return des;
	}

	public void setDes(String des) {
		this.des = des;
	}

	public String getDebugURL() {
		return debugURL;
	}

	public void setDebugURL(String debugURL) {
		this.debugURL = debugURL;
	}

	public String getApiid() {
		return apiid;
	}

	public void setApiid(String apiid) {
		this.apiid = apiid;
	}

	public String getApiname() {
		return apiname;
	}

	public void setApiname(String apiname) {
		this.apiname = apiname;
	}
	
}
